import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
//增
public class JDBC {
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入学号：");
        int a = scanner.nextInt();
        System.out.println("请输入姓名：");
        String b = scanner.next();
        //向上转型
        DataSource dataSource = new MysqlDataSource();
        //向下转型
       /* MysqlDataSource  dataSource1 = new MysqlDataSource();
        dataSource1.setUrl("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true");
        dataSource1.setUser("root");
        dataSource1.setPassword("666666");*/
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("666666");

        Connection connection = dataSource.getConnection();

//        String sql = "insert into student values('1','张三')";
        String sql = "insert into student values (?,?)";//?作为占位符 用于替换
        PreparedStatement statement = connection.prepareStatement(sql);
        //动态构造sql 索引从1开始.
        statement.setInt(1,a);
        statement.setString(2,b);
        int n = statement.executeUpdate();
        System.out.println("n = " + n);
        //释放资源
        statement.close();
        connection.close();
    }
}
